package my.suveng.nettyhello.module.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * create at 2018/10/20
 * author: suveng
 * email: suveng@163.com
 * 自定义处理器，用于返回hello netty
 **/
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {


    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
//        获取channel
            Channel channel = ctx.channel();
//        显示客户端远程地址
            System.out.println(channel.remoteAddress());
//定义发送的消息
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,netty", CharsetUtil.UTF_8);
//        构建一个http response
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
//        为响应增加一个数据类型和长度
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
//        把响应刷到客户端
            ctx.writeAndFlush(defaultFullHttpResponse);

        }
    }
}
